from fastapi import HTTPException
from tortoise.expressions import Q

from app.core.crud import CRUDBase
from app.models.admin import Dept, User
from app.schemas.depts import DeptCreate, DeptUpdate


class DeptController(CRUDBase[Dept, DeptCreate, DeptUpdate]):
    """
    部门管理
    """
    def __init__(self):
        super().__init__(model=Dept)

    async def tree_list(self, code, name, status):
        """
        获取部门树
        """
        q = Q()
        if code:
            q &= Q(code__contains=code)
        if name:
            q &= Q(name__contains=name)
        if status:
            q &= Q(status=status)
        dept_list = await self.model.filter(q).order_by("order", "id")
        dept_list = [await dept.to_dict() for dept in dept_list]

        # 搜索时不返回树形结构
        if code or name:
            return dept_list

        # 转换成菜单树形结构
        dept_dict = {dept["id"]: dept for dept in dept_list}
        for dept in dept_list:
            if dept["parent_id"] and dept["parent_id"] in dept_dict:
                if "children" not in dept_dict[dept["parent_id"]]:
                    dept_dict[dept["parent_id"]]["children"] = []
                dept_dict[dept["parent_id"]]["children"].append(dept)

        return list(filter(lambda x: x["parent_id"] == 0, dept_list))


    async def delete(self, dept_id: int):
        """
        删除部门
        """
        # 检查是否存在子部门
        children = await self.model.filter(parent_id=dept_id).first()
        if children:
            raise HTTPException(500, "该部门存在子部门，无法删除")

        # 检查是否有用户关联到该部门
        user = await User.filter(dept_id=dept_id).first()
        if user:
            raise HTTPException(500, "该部门存在关联用户，无法删除")

        # 执行删除操作
        await super().remove(dept_id)


dept_controller = DeptController()
